import json
from datetime import datetime

from django.shortcuts import render
from django.views import View
from django.core.paginator import Paginator
from django.http import HttpResponse, JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from rest_framework import generics
from rest_framework.generics import GenericAPIView
from rest_framework.pagination import PageNumberPagination

from user_app.models import Users
from .models import Communitys,Comments,upvote
from .utils.qiniu import upload_file
from .serializers import CommunitySerializerComents,CommunitySerializerComentsvote
from .utils.b64 import cookie_base64_encoded_required,bs64_encoded,bs64_decoded
# Create your views here.



class user_Com_page(PageNumberPagination):
    page_size = 3
    # max_page_size = 2
    # page_query_param = 'page'
    # page_size_query_param = 'pagesize'

'''
写一个类视图，通过POST方式提交数据，将数据保存到t_community表中
'''

@method_decorator(csrf_exempt, name='dispatch')
class CommunityView(View):
    def post(self, request):
        try:
            user = Users.objects.get(id=bs64_decoded(request.COOKIES.get('user_id')))
        except Users.DoesNotExist:
            return JsonResponse({'code': 400, 'msg': '用户不存在,重新登录'})
        # 获取请求体中的数据
        title = request.POST.get('title') if request.POST.get('title') else "无标题"
        content = request.POST.get('content')
        imgs_list = request.FILES.getlist('file')   # 获取所有图片文件
        img1_file = imgs_list[0] if len(imgs_list) > 0 else None
        img2_file = imgs_list[1] if len(imgs_list) > 1 else None
        img3_file = imgs_list[2] if len(imgs_list) > 2 else None
        create_time = request.POST.get('createtime')
        dt_time = datetime.fromtimestamp(float(create_time) / 1000.0)  # 将时间戳转换为datetime对象
        # 处理图片文件，上传到七牛云存储
        img1_url = f'{settings.BUCKET_URL}/{upload_file(settings.AK, settings.SK, img1_file)}' if img1_file else None
        img2_url = f'{settings.BUCKET_URL}/{upload_file(settings.AK, settings.SK, img2_file)}' if img2_file else None
        img3_url = f'{settings.BUCKET_URL}/{upload_file(settings.AK, settings.SK, img3_file)}' if img3_file else None
        # 将数据保存到数据库中
        sqldata = Communitys.objects.create(title=title, content=content, image1=img1_url,
                             image2=img2_url, image3=img3_url, create_time=dt_time,
                             user_id=user)
        sqldata.save()
        return JsonResponse({'code': 200, 'msg': '发布成功'})

@method_decorator(csrf_exempt, name='dispatch')
class user_CommunityListView(View):
    def get(self, request):
        queryset = Communitys.objects.filter(user_id=bs64_decoded(request.COOKIES.get('user_id')))
        # queryset = Communitys.objects.filter(user_id=18)
        items_per_page = request.GET.get('page_size', 3)  # 每页显示的项目数
        paginator = Paginator(queryset, items_per_page)  # 创建分页器对象
        page_number = request.GET.get('page', 1)  # 获取当前请求的页码，默认为1
        page_obj = paginator.get_page(page_number)  # 获取当前页码对应的页面对象
        res = CommunitySerializerComents(page_obj,many=True).data  # queryset.__len__()
        if res:
            res[0]['total'] = queryset.__len__()
        else:
            return JsonResponse({"msg":"nullcommunity","code":200}, safe=False)
        return JsonResponse(res, safe=False)


# 获取了所有的社区数据
@method_decorator(csrf_exempt, name='dispatch')
class CommunityListView(generics.ListCreateAPIView):
    queryset = Communitys.objects.all().order_by('create_time')
    serializer_class = CommunitySerializerComentsvote
    pagination_class = user_Com_page

    def get_serializer_context(self):
        context = super().get_serializer_context()
        context['request'] = self.request.__getattribute__("_request")  # 将 request 添加到上下文中
        return context



@method_decorator(csrf_exempt, name='dispatch')
class CommunityDestroyView(View):
    def delete(self,request,pk):
        try:
            community_info = Communitys.objects.get(id=pk)
        except Communitys.DoesNotExist:
            return JsonResponse({'code': 400, 'msg': '删除失败'})
        else:
            community_info.delete()
            return JsonResponse({'code': 200, 'msg': '删除成功'})


@method_decorator(csrf_exempt, name='dispatch')
class givelikeView(GenericAPIView):
    def put(self, request, pk, orlike):
        try:
            community_info = Communitys.objects.get(id=pk)
            user = Users.objects.get(id=bs64_decoded(request.COOKIES.get('user_id')))
        except Communitys.DoesNotExist:
            return JsonResponse({'code': 400, 'msg': '点赞失败'})
        else:
            if orlike == "true":  # orlike为True，表示允许点赞
                community_info.giveLike += 1
                community_info.save()
                count = community_info.giveLike
                # 如果之前有点赞或者取消行为，在数据库中有相应的案例，就执行简单的改变likeStatus
                u_v = upvote.objects.filter(community=community_info).filter(user_upvote=user).first()
                if u_v:
                    u_v.likeStatus = 1
                    u_v.save()
                else:  # 否则，创建新的点赞记录
                    u_vote = upvote.objects.create(community=community_info,
                                          user_upvote=user,
                                          likeStatus=1)
                    u_vote.save()
                return JsonResponse({'code': 200, 'msg': '点赞成功', 'count': count})
            else:
                community_info.giveLike -= 1
                community_info.save()
                count = community_info.giveLike
                u_v = upvote.objects.filter(community=community_info).filter(user_upvote=user).first()
                if u_v:
                    u_v.likeStatus = 0
                    u_v.save()
                return JsonResponse({'code': 200, 'msg': '取消点赞成功', 'count': count})

@csrf_exempt
def user_Comments(request):
    """
    谁评论的
    评论了哪条数据
    返回评论的那一条数据的评论信息
    """
    if request.method == 'POST':
        try:
            user = Users.objects.get(id = bs64_decoded(request.COOKIES.get('user_id')))  # 获取谁评论的用户信息
        except Users.DoesNotExist:
            return JsonResponse({'code': 400, 'msg': '用户不存在,重新登录',"data":'null'})
        else:
            data = json.load(request)
            com_id = data.get('com_id')  # 获取评论的哪条数据
            comment = data.get('comment')  # 获取评论的内容
            community = Communitys.objects.get(id=com_id)  # 获取评论的社区信息
            sqldata = Comments.objects.create(content=comment, create_time=datetime.now(), community=community, user_id=user)
            sqldata.save()
            # 将数据保存到数据库后，返回评论的那条社区动态的信息序列化
            res_data = CommunitySerializerComents(community, many=False).data
            return JsonResponse({'code': 200, 'msg': '评论成功', 'data': res_data},safe=False)




